<?php
/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 2.0.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
namespace xg;
use helper\Arr;
use helper\Str;

class Form {
	protected $options = [];
	public static $defOptions = [];
	public static function create(array $options) {
		$obj = new static($options);
		return $obj->build();
	}
	public function __construct(array $options) {
		$options=Hook::create('form.init')->default($options)->run($options)->last();
		$this->options = Arr::extend(self::$defOptions,$options);
		foreach($this->options as $key=>$val){
			unset($this->options[$key]);
			$this->options[Str::camel($key)] = $val;
		}
	}
	public function build() {
		$options = $this->options;
		if(method_exists($this,$type=$options['type'])) {
			return $this->$type();
		}
		$content = $this->element();
		$content = Hook::create('form.build')->default($content)->run($content)->last();
		return $content;
	}
	public function textarea() {
		$this->options['element']='textarea';
		$this->options['isCloseEl']=true;
		$html = $this->element();
		return $html;
	}
	public function element($options=null) {
		if(!$options) {
			$options = $this->options;
		}
		
		$attrs = is_array($options['attrs'])?$options['attrs']:[];

		$attrs['type'] = $options['type']?$options['type']:'text';
		if(isset($options['value'])) {
			$attrs['value'] = $options['value'];
		}
		if(isset($options['name'])) {
			$attrs['name'] = $options['name'];
		}
		if(!isset($options['autocomplete'])) {
			$attrs['autocomplete'] = 'off';
		}

		$keys = ['id','rows','placeholder','required','disabled','readonly','autofocus','autocomplete','minlength'];
		foreach($keys as $key) {
			if($options[$key]) {
				$attrs[$key] = $options[$key];
			}
		}
		$attrs['class'] = Arr::join(array_filter([$options['inputClass']]),' ');

		if($options['model']=='base') {
			$attrs['class'] = Arr::join(array_filter([$attrs['class'],$options['class']]),' ');
		}

		$attrs['data-hash'] = $this->hashName($options['name']);

		$element=$options['element']?$options['element']:'input';

		$html = '<'.$element;
		foreach($attrs as $key=>$val) {
			$html .= ' '.$key.'="'.str_replace('"','&quot;',$val).'"';
		}
		if($options['isCloseEl']) {
			$html.='></'.$element.'>';
		}else{
			$html.=' />';
		}
		if($options['model']!='base') {
			$html = $this->wrap($html);
		}
		return $html;
	}
	public function upload() {
		$options = $this->options;
		$input = $this->element([
			'name'=>$options['name'],
			'model'=>'base',
			'id'=>'upload-'.$this->hashName($options['name']),
			'inputClass'=>'upload-input-'.$this->hashName($options['name'])
		]);
		$buttonText = $options['buttonText']?$options['buttonText']:'上传文件';
		$button = '<button class="xg-button xg-upload-button" type="button">'.$buttonText.'</button>';
		$script = $this->uploadScript();
		$html = '<div class="xg-form-item-upload xg-flex xg-flex-align-center">'.$input.$button.$script.'</div>';
		if($options['model']!='base') {
			$html = $this->wrap($html);
		}
		return $html;
	}
	public function uploadScript() {
		$url = $this->options['url']?$this->options['url']:\xg\facade\Route::buildUrl('upload');
		$hash = $this->hashName($this->options['name']);
		$html = "<script>xg.mod('upload',function(){
			const \$input=\$('.upload-input-$hash');
			const \$btn=\$input.next('button');
			xg.upload({
				url:'$url',
				done:function(data){
					if(data.url){
						\$input.val(data.url).change();
						xg.success(data.message||'上传成功');
					}else{
						xg.error(data.message||'上传失败');
					}
				}
			}).bind(\$btn);
		});</script>";
		return $html;
	}
	public function itemClass($options=null) {
		if(!$options) {
			$options = $this->options;
		}
		if($options['model']=='col'){
			$classname = 'xg-flex xg-flex-col xg-form-col-item';
		}elseif($options['model']=='row'){
			$classname = 'xg-flex xg-flex-align-center xg-form-row-item';
		}elseif($options['model']=='base'){
			return '';
		}
		return Arr::join(array_filter([
			'xg-form-item',
			'xg-form-item-'.$options['type'],
			'xg-form-item-'.$options['name'],
			'xg-form-item-'.$this->hashName($options['name']),
			$options['class'],
			$classname
		]),' ');
	}
	public function wrap($html,$options=null) {
		if(!$options) {
			$options = $this->options;
		}
		$hash = $this->hashName($options['name']);
		$classname = $this->itemClass();
		return '<div class="'.$classname.'" data-hash="'.$hash.'">'.$this->label($options).$html.'</div>';
	}
	public function label($options=null) {
		if(!$options) {
			$options = $this->options;
		}
		if(!$options['label']) {
			return '';
		}
		if($options['helpid']) {
			$help=$this->helpLink($options['helpid']);
			if($help=trim($help)){
				$help='<span class="xg-form-item-help">'.$help.'</span>';
			}
		}
		if($options['helplink']) {
			if($help=trim($help)) {
				$help='<span class="xg-form-item-help">'.$help.'</span>';
			}
		}
		if($options['tips']) {
			$tips = '<span class="xg-form-item-tips">'.$options['tips'].'</span>';
		}
		$label = $options['label']?$options['label']:$options['name'];
		return '<label class="xg-form-label">'.$help.$label.$tips.'</label>';
	}
	protected function hashName($name) {
		return substr(md5($name),0,6);
	}
	protected function helpLink($helpid=0) {
		$help_url=\xg\facade\Config::get('site.help_url');
		if(!$help_url){
			$and = strpos($help_url,'?')===false?'?':'&';
			$help_url = $help_url.$and.'helpid='.$helpid;
			return '<a href="'.$help_url.'" target="_blank"></a>';
		}
		return '';
	}
}
?>